<template>
  <div class="x-upload">
    <el-upload slot="append" :show-file-list="false" :action="$ala.clientUploadApi()" :on-success="uploadSuccess" :on-progress="progressChange" :on-exceed="handleExceed">
      <el-input readonly v-model="viewModel" class="input-with-select" :disabled="true">
        <el-button icon="el-icon-search" slot="append" type="primary">文件上传</el-button>
      </el-input>
    </el-upload>
    <div class="x-upload-loading" v-if="loading" v-loading="loading" element-loading-background="#ffffff">
      <div class="x-upload-text">{{progressNum}}%</div>
    </div>
  </div>
</template>

<script>
  import ala from 'ala'
  export default {
    model: {
      prop: 'dataModel',
      event: 'change'
    },
    props: {
      dataModel: {}
    },
    data () {
      return {
        viewModel: '',
        loading: false,
        progressNum: 0
      }
    },
    mounted () {
      this.init()
    },
    methods: {
      async init () {
        this.viewModel = this.dataModel
      },
      uploadSuccess (res, file) {
        this.loading = false
        if (res && res.result) {
          this.$message.success('上传成功')
          this.viewModel = res.result.path
        } else {
          this.$message.error('上传失败，请重新上传')
        }
      },
      handleExceed (files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
      },
      beforeRemove (file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`)
      },
      progressChange (event, file, fileList) {
        this.loading = true
        this.progressNum = file.percentage.toFixed(0)
        // file.percentage.toFixed(0)
      }
    },
    watch: {
      viewModel: {
        deep: true,
        handler (val) {
          this.$emit('change', this.viewModel)
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .x-upload {
    width: 80%;
    display: flex;
    .el-upload {
      width: 100%;
    }
    .el-input__inner {
      cursor: pointer;
    }
    .x-upload-loading {
      width: 40px;
      height: 40px;
      position: relative;
      .x-upload-text {
        width: 40px;
        height: 40px;
        position: absolute;
        z-index: 999999999;
        text-align: center;
      }
    }
  }
</style>
